package sk.marek.barak.client;

import java.util.Iterator;
import java.util.List;

import sk.marek.barak.shared.MessageServiceFactory;
import sk.marek.barak.shared.TokenServiceFactory;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.Widget;

public class UserTab extends Composite {
	
	private static final int CHAT_BOX_UPPER_DIVISION =281;
	
	private TokenServiceAsync tokenService;
	private MessageServiceAsync messageService;
	
	//User identification
	private String userNickName;
	private String userID;

	//Chat panel
	private UserChat chat;
	
	//Container for chat panel
	private PopupPanel popup;
	
	//Reference to parent container
	private FlexTable chatTable;
	
	
	//UI items
	private Label name;
	private PushButton closeButton;
	private PushButton maxButton;
	
	
	/**
	 * 
	 * @param nam 
	 * user name shown in user tab and chat panel
	 * @param userID
	 * user ID for communication and user description 
	 * @param table
	 * Reference for user widget, for widget manipulation
	 *
	 */
	
	public UserTab(String nam,String userID,FlexTable table){
		
		this.userNickName = nam;
		this.userID = userID;
		this.chatTable = table;
		
		
		name= new Label(nam);
		chat = new UserChat(this);		
		
		AbsolutePanel absolutePanel = new AbsolutePanel();
		initWidget(absolutePanel);
		absolutePanel.setSize("219px", "28px");
		
		absolutePanel.add(name, 0, 0);
		name.setSize("145px", "23px");
		
		closeButton= new PushButton("x");
		absolutePanel.add(closeButton, 183, 0);
		closeButton.setSize("24px", "17px");
		closeButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				closeChatTab();
				
			}
		});
		
		String button = new String("\u25FB");
		maxButton = new PushButton(button);
		absolutePanel.add(maxButton, 147, 0);
		maxButton.setSize("24px", "17px");
		maxButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				openChat();
				
			}
		});
		
	popup = new PopupPanel();	
	popup.setWidget(chat);
	
	final Timer messageTimer = new Timer(){

		@Override
		public void run() {
			checkMessage();
			
		}
		
	};
	messageTimer.scheduleRepeating(5000);
	
	}
	
	/**
	 * 
	 * @return the ID of the user
	 *  
	 */
	public String getUserID(){
		return this.userID;
	}
	
	public String getUserName(){
		return this.userNickName;
	}

	public void openChat(){
		resetChatLocation();
		popup.show();
		setUiVisible(false);
		
	}
	public void closeChat(){
		popup.hide();
		setUiVisible(true);
		
	}
	public void resetChatLocation(){
		popup.setPopupPosition(this.getAbsoluteLeft(), this.getAbsoluteTop()-CHAT_BOX_UPPER_DIVISION);
	}
	
	//closes 
	public void closeChatTab(){
		
		if(popup.isShowing())
			closeChat();
			
		for(int i = 0;i<chatTable.getCellCount(0);i++){
			UserTab tmp = (UserTab) chatTable.getWidget(0, i);
			if(this.getUserID() == tmp.getUserID()){
				chatTable.removeCell(0, i);
				break;
				}
			}
		releocateTabs();
		
	}

	//relocates open chat window
	private void releocateTabs(){
		for(Iterator<Widget> itr = chatTable.iterator();itr.hasNext();)
			((UserTab)itr.next()).resetChatLocation();
	}
	private void setUiVisible(boolean visible){
		this.name.setVisible(visible);
		this.closeButton.setVisible(visible);
		this.maxButton.setVisible(visible);
		
	}
	
	public void sendMessage(String message){
			sendToken();
			if(messageService==null)
			messageService = MessageServiceFactory.getMessageService();
			
			messageService.sendMessage(userID, message, new AsyncCallback<Void>() {

				@Override
				public void onFailure(Throwable caught) {
					Window.alert("Failed to send message");
					
				}

				@Override
				public void onSuccess(Void result) {
					// TODO Auto-generated method stub
					
				}
			
			});
			
		}
	public void checkMessage(){
		if(messageService==null)
			messageService = MessageServiceFactory.getMessageService();
		messageService.getMessage(userID, new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(String result) {
				if(result!=null){
				chat.sendMessage(userNickName+": "+result);
				
				if(!popup.isShowing());
					//openChat();
				}
				
			}
		
		});
		
	}

 	private void sendToken(){
		if(tokenService==null){
			tokenService = TokenServiceFactory.getTokenService();
			tokenService.sendToken(userID, new AsyncCallback<Void>() {
				
				@Override
				public void onSuccess(Void result) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onFailure(Throwable caught) {
					Window.alert("Cant Send token");
					
				}
			});
		}
	}



}
	
	






